<template>
  <div class="products-view mx-auto py-4" :key="route.path">
    <div class="page-title mb-3 flex justify-between items-center">
      <h1 class="text-2xl font-bold text-gray-800">
        {{ route.path === "/next-products" ? "近效期商品" : "全部商品" }}
      </h1>
      <div class="text-sm text-gray-600">
        共
        <span class="text-red-600 font-medium">{{ totalProducts }}</span> 个商品
      </div>
    </div>

    <!-- 过滤条件区域 - 可折叠 -->
    <el-card class="filter-collapse mb-4" shadow="never">
      <template #header>
        <div class="filter-header flex justify-between items-center">
          <div class="selected-filters w-full">
            <div class="flex items-center">
              <span class="text-gray-700 font-semibold">筛选条件</span>
              <span v-if="!hasActiveFilters" class="text-gray-400 ml-2"
                >未选择筛选条件</span
              >
            </div>
          </div>

          <!-- 展开/折叠图标 -->
          <div
            class="flex items-center text-gray-500 ml-4 shrink-0 cursor-pointer"
            @click="isFilterExpanded = !isFilterExpanded"
          >
            <span class="mr-2 text-sm">{{
              isFilterExpanded ? "收起筛选" : "展开筛选"
            }}</span>
            <el-icon
              :class="{
                'rotate-180': !isFilterExpanded,
                'transform transition-transform': true,
              }"
            >
              <ArrowUp />
            </el-icon>
          </div>
        </div>
      </template>

      <!-- 折叠区内容 -->
      <div v-show="isFilterExpanded" class="filter-content">
        <!-- 各类筛选条件水平排列 -->
        <div
          class="filter-category py-2 border-b border-gray-100 flex flex-wrap items-start"
        >
          <div
            class="filter-label text-gray-700 mr-2 w-16 flex-shrink-0 text-sm"
          >
            品牌：
          </div>
          <div class="filter-options flex-1 flex flex-wrap">
            <div
              v-for="brand in topBrands"
              :key="brand.brandID"
              class="filter-option me-3 mb-1"
            >
              <div
                class="custom-brand-checkbox"
                :class="{ 'is-checked': filters.brand.includes(brand.brandID.toString()) }"
                @click="toggleBrand(brand.brandID)"
              >
                <div class="brand-content">
                  <img 
                    v-if="brand.url" 
                    :src="brand.url" 
                    :alt="brand.name"
                    class="brand-logo"
                    @error="handleBrandImageError"
                  >
                  <span class="brand-name">{{ brand.name }}</span>
                </div>
              </div>
            </div>
            <div
              v-if="isMoreBrandsVisible"
              v-for="brand in moreBrands"
              :key="brand.brandID"
              class="filter-option me-3 mb-1"
            >
              <div
                class="custom-brand-checkbox"
                :class="{ 'is-checked': filters.brand.includes(brand.brandID.toString()) }"
                @click="toggleBrand(brand.brandID)"
              >
                <div class="brand-content">
                  <img 
                    v-if="brand.url" 
                    :src="brand.url" 
                    :alt="brand.name"
                    class="brand-logo"
                    @error="handleBrandImageError"
                  >
                  <span class="brand-name">{{ brand.name }}</span>
                </div>
              </div>
            </div>
            <div class="filter-more ml-2">
              <el-button type="text" size="small" @click="toggleMoreBrands">
                {{ isMoreBrandsVisible ? "收起" : "更多" }}
                <el-icon
                  :class="{
                    'rotate-180': isMoreBrandsVisible,
                    'transform transition-transform': true,
                  }"
                  class="ml-1"
                >
                  <ArrowUp />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <div
          class="filter-category py-2 border-b border-gray-100 flex flex-wrap items-start"
        >
          <div
            class="filter-label text-gray-700 mr-2 w-16 flex-shrink-0 text-sm"
          >
            分类：
          </div>
          <div class="filter-options flex-1 flex flex-wrap">
            <div class="filter-option me-3 mb-1">
              <el-checkbox
                v-model="filters.category"
                label="全部"
                size="small"
                border
                >全部</el-checkbox
              >
            </div>
            <div
              v-for="category in categoryTree"
              :key="category.id"
              class="category-item me-3 mb-1 relative"
              @mouseenter="showSubcategory(category.id)"
            >
              <el-checkbox
                :model-value="filters.category.includes(category.id)"
                size="small"
                border
                @change="() => selectCategory(category.id, true)"
              >
                {{ category.label }}
              </el-checkbox>

              <!-- 二级分类下拉菜单 -->
              <div
                v-if="
                  category.children &&
                  category.children.length > 0 &&
                  hoveredCategoryId === category.id
                "
                class="subcategories absolute left-0 top-full mt-1 bg-white shadow-md rounded-md p-3 z-10 min-w-[600px]"
                @mouseenter="keepSubcategoryOpen(category.id)"
                @mouseleave="hideSubcategory"
              >
                <div class="subcategory-wrapper grid grid-cols-4 gap-2">
                  <div
                    v-for="subcat in category.children"
                    :key="subcat.id"
                    class="subcategory-item flex flex-col cursor-pointer"
                    @click="selectCategory(subcat.id)"
                  >
                    <div
                      class="subcategory-label text-xs font-medium pb-1 hover:text-primary-500 whitespace-nowrap overflow-hidden text-ellipsis"
                      :class="{
                        'text-primary-500': filters.category.includes(
                          subcat.id
                        ),
                      }"
                    >
                      {{ subcat.label }}
                    </div>

                    <!-- 三级分类列表 -->
                    <div
                      v-if="subcat.children && subcat.children.length > 0"
                      class="third-level flex flex-wrap gap-1"
                    >
                      <div
                        v-for="thirdCat in subcat.children"
                        :key="thirdCat.id"
                        class="third-category-item text-xs text-gray-500 hover:text-primary-500 whitespace-nowrap overflow-hidden text-ellipsis"
                        @click.stop="selectCategory(thirdCat.id)"
                      >
                        {{ thirdCat.label }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="filter-category py-2 flex flex-wrap items-start">
          <div
            class="filter-label text-gray-700 mr-2 w-16 flex-shrink-0 text-sm"
          >
            库存：
          </div>
          <div class="filter-options flex-1 flex flex-wrap">
            <div class="filter-option me-3 mb-1">
              <el-radio v-model="filters.stock" label="" size="small" border
                >全部</el-radio
              >
            </div>
            <div class="filter-option me-3 mb-1">
              <el-radio
                v-model="filters.stock"
                label="in_stock"
                size="small"
                border
                >有库存</el-radio
              >
            </div>
            <div class="filter-option me-3 mb-1">
              <el-radio
                v-model="filters.stock"
                label="out_of_stock"
                size="small"
                border
                >无库存</el-radio
              >
            </div>
          </div>
        </div>

        <!-- 属性筛选 -->
        <div
          class="filter-category py-2 border-b border-gray-100 flex flex-wrap items-start"
        >
          <div
            class="filter-label text-gray-700 mr-2 w-16 flex-shrink-0 text-sm"
          >
            属性：
          </div>
          <div class="filter-options flex-1 flex flex-wrap">
            <div
              v-for="attr in attributeOptions"
              :key="attr.value"
              class="filter-option me-3 mb-1"
            >
              <el-checkbox
                v-model="filters.attribute"
                :label="attr.value"
                size="small"
                border
                >{{ attr.label }}</el-checkbox
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 已选筛选条件显示 - 移到折叠区域外部 -->
      <div
        v-if="hasActiveFilters"
        class="selected-filters-area px-3 py-2 flex flex-wrap items-center bg-gray-50 rounded-b-md"
      >
        <div class="mr-3 text-gray-600 text-sm font-medium">已选条件:</div>
        <div class="selected-tags flex flex-wrap gap-2">
          <el-tag
            v-if="filters.brand.length > 0"
            closable
            @close="filters.brand = []"
            class="flex items-center"
            type="info"
            effect="light"
            size="small"
          >
            <span class="tag-label">品牌:</span>
            {{
              filters.brand
                .map(id => {
                  const brand = [...topBrands, ...moreBrands].find(b => b.brandID.toString() === id)
                  return brand ? brand.name : id
                })
                .join(", ")
            }}
          </el-tag>
          <el-tag
            v-if="filters.category.length > 0"
            closable
            @close="filters.category = []"
            class="flex items-center"
            type="info"
            effect="light"
            size="small"
          >
            <span class="tag-label">分类:</span>
            {{
              getDisplayCategoryIds()
                .map((id) => getCategoryName(id))
                .join(", ")
            }}
          </el-tag>
          <el-tag
            v-if="filters.expiry"
            closable
            @close="filters.expiry = ''"
            class="flex items-center"
            type="info"
            effect="light"
            size="small"
          >
            <span class="tag-label">效期:</span>
            {{ getExpiryLabel(filters.expiry) }}
          </el-tag>
          <el-tag
            v-if="filters.stock"
            closable
            @close="filters.stock = ''"
            class="flex items-center"
            type="info"
            effect="light"
            size="small"
          >
            <span class="tag-label">库存:</span>
            {{ getStockLabel(filters.stock) }}
          </el-tag>
          <el-tag
            v-if="filters.attribute.length > 0"
            closable
            @close="filters.attribute = []"
            class="flex items-center"
            type="info"
            effect="light"
            size="small"
          >
            <span class="tag-label">属性:</span>
            {{ getAttributeLabels(filters.attribute) }}
          </el-tag>
        </div>
        <div class="ml-auto">
          <el-button type="info" plain size="small" @click="resetFilters"
            >清空筛选</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="applyFilters"
            class="ml-2"
            >确认</el-button
          >
        </div>
      </div>
    </el-card>

    <!-- 排序选项 -->
    <div
      class="sorting-options bg-white rounded-lg shadow-sm p-2 mb-4 flex justify-between items-center"
    >
      <div class="sort-buttons flex">
        <el-radio-group v-model="sortBy" size="small">
          <el-radio-button label="default">综合排序</el-radio-button>
          <el-radio-button label="price_asc">价格从低到高</el-radio-button>
          <el-radio-button label="price_desc">价格从高到低</el-radio-button>
        </el-radio-group>
      </div>
      <!-- <div>
        <el-switch
          v-model="onlyShowInStock"
          active-text="只看有货"
          inactive-text=""
        />
      </div> -->
    </div>

    <!-- 商品展示区域 -->
    <div
      class="product-grid grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4"
    >
      <div
        v-for="product in products"
        :key="product.id"
        class="product-card group relative bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
        :class="{ 'cursor-pointer': route.path !== '/next-products' }"
        @click="
          route.path !== '/next-products'
            ? navigateToDetail(product.id)
            : undefined
        "
      >
        <!-- 图片区域 -->
        <div
          class="product-image relative overflow-hidden h-40 bg-gradient-to-br from-gray-50 via-white to-slate-50 flex items-center justify-center"
        >
          <img
            :src="product.imgUrl || '/images/no.jpg'"
            :alt="product.oracleGoodsName"
            class="w-full h-full object-contain transition-transform duration-300 group-hover:scale-105"
            @error="handleImageError"
            @click.stop="
              route.path !== '/next-products'
                ? navigateToDetail(product.id)
                : undefined
            "
          />

          <!-- 图片右上角库存 -->
          <div class="absolute top-2 right-2">
            <span
              class="stock-badge"
              :class="getStockStatusClass(product.storNum)"
            >
              {{ getStockStatusText(product.storNum) }}
            </span>
          </div>
        </div>

        <!-- 信息区域 -->
        <div class="product-info p-3">
          <!-- 商品名称 -->
          <h3
            class="product-name text-sm font-medium text-gray-900 leading-tight mb-2 line-clamp-2 group-hover:text-blue-600 transition-colors"
          >
            {{ product.oracleGoodsName }}
          </h3>

          <!-- 厂家 -->
          <div class="manufacturer text-xs text-gray-500 mb-2 truncate">
            {{ product.manufacturer }}
          </div>

          <!-- 规格和包装信息 -->
          <div class="specs-row flex items-center justify-between mb-2">
            <div class="flex items-center gap-1">
              <span class="spec-tag">{{ product.goodsSpec }}</span>
              <span class="spec-tag">{{ product.unit }}</span>
            </div>
            <div
              v-if="product.midpack > 1"
              class="package-info text-xs text-gray-600"
            >
              {{ product.midpack }}{{ product.unit }}/包
              <span v-if="product.isMidpackSaleDisabled === 1" class="no-split"
                >不拆零</span
              >
            </div>
          </div>

          <!-- 近效期信息 -->
          <div v-if="product.nearestExpiredDate" class="expiry-row mb-2">
            <span class="expiry-tag"
              >有效期 {{ route.path === '/next-products' ? formatDate(product.nearestExpiredDate) : formatDate(product.expiredDate) }}</span
            >
          </div>
          <div class="price-section">
            <span class="product-price text-lg font-bold text-red-600">
              {{
                formatPriceAuth(
                  product.price,
                  !!userStore.token,
                  userStore.userInfo?.discount,
                  product.noDiscounts
                )
              }}
            </span>

            <span
              v-if="userStore.userInfo?.discount && product.noDiscounts !== 1"
              class="text-gray-400 text-sm ml-2 line-through"
            >
              {{ formatPriceAuth(product.price, !!userStore.token) }}
            </span>
          </div>

          <!-- 价格和操作区 -->
          <div class="bottom-section flex items-center justify-between">
            <div class="action-section flex items-center gap-2">
              <el-input-number
                v-model="product.quantity"
                :min="getMinQuantity(product)"
                :max="
                  Math.max(
                    getMinQuantity(product),
                    Math.floor(parseFloat(product.storNum))
                  )
                "
                :step="getQuantityStep(product)"
                size="small"
                class="quantity-input w-30"
                :disabled="parseFloat(product.storNum) <= 0"
                @click.stop
              />
              <el-button
                :type="route.path === '/next-products' ? 'success' : 'primary'"
                size="small"
                :disabled="
                  parseFloat(product.storNum) <= 0 || !isValidQuantity(product) || isCreatingOrder || addingToCartIds.has(product.goodsId)
                "
                :loading="route.path === '/next-products' ? isCreatingOrder : addingToCartIds.has(product.goodsId)"
                @click.stop="
                  route.path === '/next-products'
                    ? createNextValOrder(product)
                    : addToCart(product)
                "
                class="cart-btn"
              >
                <span v-if="route.path !== '/next-products'">{{ addingToCartIds.has(product.goodsId) ? '添加中...' : '加入购物车' }}</span>
                <span v-else>{{ isCreatingOrder ? '下单中...' : '下单' }}</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="products.length === 0"
      description="未找到符合条件的商品"
      :image-size="200"
    ></el-empty>

    <!-- 分页 -->
    <div class="pagination flex justify-center mt-6">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 60, 80]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalProducts"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        :page-size-text="'每页条数'"
        :prev-text="'上一页'"
        :next-text="'下一页'"
        :jumper-text="'跳至'"
        :total-text="'共'"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowUp } from "@element-plus/icons-vue";
import {
  getGoodsList,
  getGoodsTypeList,
  getNextGoodsList,
} from "@/api/modules/goods";
import type { GoodsType, Goods } from "@/api/modules/goods";
import { useCartStore } from "@/stores/cart";
import { useUserStore } from "@/stores/user";
import { getStockStatusText, getStockStatusClass } from "@/lib/stockUtils";
import { formatPriceAuth } from "@/lib/utils";
import { getCartList, deleteCart } from "@/api/modules/cart";
import { getBrandList, type BrandItem } from '@/api/modules/layout'

// 搜索关键词
const searchKeyword = ref("");

// 获取路由实例
const route = useRoute();
const router = useRouter();

// 定义商品接口
interface Product {
  id: string;
  goodsId: string;
  oracleGoodsName: string;
  manufacturer: string;
  price: string;
  imgUrl: string;
  storNum: string;
  sold: number;
  category: string;
  goodsSpec: string;
  isLowStock: boolean;
  approvalNo: string;
  formula: string;
  midpack: number;
  qty: string;
  planCate: string | null;
  isMidpackSaleDisabled: number;
  gCategory: string;
  qCategory: string;
  attribute: string;
  typeName: string;
  nearestExpiredDate: string;
  expiredDate: string;
  noDiscounts: number;
  quantity: number;
  unit: string;
  isPres: number;
  isNextValPrice?: boolean;
  nearStorNum?: string;
}

// 定义分类树节点接口
interface CategoryTreeNode {
  id: number;
  label: string;
  selectable: boolean;
  children: CategoryTreeNode[];
}

// 过滤区域展开状态
const isFilterExpanded = ref(false);

// 定义过滤条件
const filters = reactive({
  brand: [] as string[],
  category: [] as number[],
  expiry: "",
  stock: "",
  attribute: [] as number[],
});

// 从 URL 读取过滤条件
function loadFiltersFromUrl() {
  const query = route.query;

  if (query.brand) {
    filters.brand = Array.isArray(query.brand)
      ? query.brand.map(String)
      : [query.brand];
  }

  if (query.category) {
    filters.category = Array.isArray(query.category)
      ? query.category.map(Number)
      : [Number(query.category)];
  }

  if (query.expiry) {
    filters.expiry = String(query.expiry);
  }

  if (query.stock) {
    filters.stock = String(query.stock);
  }

  if (query.attribute) {
    filters.attribute = Array.isArray(query.attribute)
      ? query.attribute.map(Number)
      : [Number(query.attribute)];
  }

  // 设置搜索关键词
  if (query.keyWord) {
    searchKeyword.value = String(query.keyWord);
  }
}

// 更新 URL 查询参数
function updateUrlQuery() {
  const query: Record<string, any> = {};

  if (filters.brand.length > 0) {
    query.brand = filters.brand;
  }

  if (filters.category.length > 0) {
    query.category = filters.category;
  }

  if (filters.expiry) {
    query.expiry = filters.expiry;
  }

  if (filters.stock) {
    query.stock = filters.stock;
  }

  if (filters.attribute.length > 0) {
    query.attribute = filters.attribute;
  }

  // 使用 replace 而不是 push 来避免历史记录堆积
  router.replace({ query });
}

// 监听过滤条件变化
watch(
  filters,
  () => {
    updateUrlQuery();
  },
  { deep: true }
);

// 监听路由变化
watch(
  () => route.query,
  () => {
    loadFiltersFromUrl();
  },
  { immediate: true }
);

// 监听搜索关键词变化
watch(searchKeyword, () => {
  // 重置分页到第一页
  currentPage.value = 1;
  // 重新获取商品列表
  fetchGoodsList();
});

// 品牌展开状态
const isMoreBrandsVisible = ref(false);
// 当前悬停的分类ID
const hoveredCategoryId = ref<number | null>(null);

// 切换品牌更多显示
function toggleMoreBrands() {
  isMoreBrandsVisible.value = !isMoreBrandsVisible.value;
}

// 显示子分类
function showSubcategory(categoryId: number) {
  hoveredCategoryId.value = categoryId;
}

// 保持子分类菜单打开
function keepSubcategoryOpen(categoryId: number) {
  hoveredCategoryId.value = categoryId;
}

// 隐藏子分类
function hideSubcategory() {
  hoveredCategoryId.value = null;
}

// 选择分类
function selectCategory(categoryId: number, isParent: boolean = false) {
  // 如果是一级分类，获取所有子分类ID
  if (isParent) {
    const getAllSubcategoryIds = (category: CategoryTreeNode): number[] => {
      let ids: number[] = [];
      if (category.children && category.children.length > 0) {
        category.children.forEach((subcat) => {
          ids.push(subcat.id);
          if (subcat.children && subcat.children.length > 0) {
            ids = ids.concat(getAllSubcategoryIds(subcat));
          }
        });
      }
      return ids;
    };

    const category = categoryTree.value.find((cat) => cat.id === categoryId);
    if (category) {
      const allSubcategoryIds = getAllSubcategoryIds(category);

      // 如果已经选择了这个分类，则移除它和所有子分类
      if (filters.category.includes(categoryId)) {
        filters.category = filters.category.filter(
          (id) => id !== categoryId && !allSubcategoryIds.includes(id)
        );
      } else {
        // 否则添加这个分类和所有子分类
        filters.category = [
          ...new Set([...filters.category, categoryId, ...allSubcategoryIds]),
        ];
      }
    }
  } else {
    // 如果是二级或三级分类，保持原有逻辑
    if (filters.category.includes(categoryId)) {
      filters.category = filters.category.filter((item) => item !== categoryId);
    } else {
      filters.category.push(categoryId);
    }
  }
  hideSubcategory();
}

// 热门品牌列表 (显示前5个)
const topBrands = ref<BrandItem[]>([])
// 更多品牌列表 (点击更多后显示)
const moreBrands = ref<BrandItem[]>([])

// 获取品牌列表数据
async function fetchBrands() {
  try {
    const response: any = await getBrandList()
    // 将品牌列表分为热门和更多两部分
    topBrands.value = response.data.slice(0, 5)
    moreBrands.value = response.data.slice(5)
  } catch (error) {
    console.error('获取品牌列表失败:', error)
    ElMessage.error('获取品牌列表失败')
  }
}

// 排序方式
const sortBy = ref("default");
const onlyShowInStock = ref(false);

// 分页
const currentPage = ref(1);
const pageSize = ref(20);
const totalProducts = ref(200); // 模拟总商品数量

// 属性选项
const attributeOptions = [
  { label: "普通药品", value: 0 },
  { label: "新品上市", value: 1 },
  { label: "热销药品", value: 2 },
  { label: "推荐药品", value: 3 },
  { label: "特价药品", value: 4 },
  { label: "畅销药品", value: 5 },
  { label: "精品药品", value: 6 },
  { label: "优选药品", value: 7 },
  { label: "限购药品", value: 8 },
];

// 检查是否有活动的过滤条件
const hasActiveFilters = computed(() => {
  return (
    filters.brand.length > 0 ||
    filters.category.length > 0 ||
    filters.expiry !== "" ||
    filters.stock !== "" ||
    filters.attribute.length > 0
  );
});

// 分类树数据
const categoryTree = ref<CategoryTreeNode[]>([]);

// 获取分类数据
async function fetchCategories() {
  try {
    const response: any = await getGoodsTypeList({
      sort: "asc",
      order: "sortNum",
    });

    if (response.code === 1000) {
      const categories = response.data as GoodsType[];

      // 构建分类树
      const buildTree = (
        items: GoodsType[],
        parentId: number | null = null
      ): CategoryTreeNode[] => {
        return items
          .filter((item) => item.parentId === parentId)
          .sort((a, b) => (a.sortNum || 0) - (b.sortNum || 0)) // 按 sortNum 正序排序
          .map((item) => ({
            id: item.id,
            label: item.name,
            selectable: true,
            children: buildTree(items, item.id),
          }));
      };

      categoryTree.value = buildTree(categories);
    }
  } catch (error) {
    console.error("获取分类数据失败:", error);
    ElMessage.error("获取分类数据失败");
  }
}

// 临时商品数据
const products = ref<Product[]>([]);

// Add to cart loading states for each product
const addingToCartIds = ref<Set<string>>(new Set());

// Transform API response to frontend product format
function transformToProduct(item: any): Product {
  const isNextProduct = route.path === "/next-products";
  return {
    id: item.id,
    goodsId: item.goodsId,
    oracleGoodsName: item.oracleGoodsName,
    manufacturer: item.manufacturer,
    price: item.price,
    imgUrl: item.mainPic,
    storNum: isNextProduct ? item.nearStorNum : item.storNum,
    sold: item.sold,
    category: item.category,
    goodsSpec: item.goodsSpec,
    isLowStock: isNextProduct
      ? Number(item.nearStorNum) <= 100
      : Number(item.storNum) <= 100,
    approvalNo: item.approvalNo,
    formula: item.formula,
    midpack: item.midpack,
    qty: item.qty,
    planCate: item.planCate,
    isMidpackSaleDisabled: item.isMidpackSaleDisabled,
    gCategory: item.gCategory,
    qCategory: item.qCategory,
    attribute: item.attribute,
    typeName: item.typeName,
    nearestExpiredDate: item.nearestExpiredDate || "",
    noDiscounts: Number(item.noDiscounts || 0),
    quantity: 1,
    unit: item.unit,
    isPres: item.isPres,
    isNextValPrice: isNextProduct ? item.isNextValPrice : undefined,
    nearStorNum: item.nearStorNum,
    expiredDate: item.expiredDate,
  };
}

// 获取商品列表
async function fetchGoodsList() {
  try {
    const isNextProduct = route.path === "/next-products";
    const params: any = {
      page: currentPage.value,
      size: pageSize.value,
      sort: sortBy.value === "price_desc" ? "desc" : "asc",
      order: sortBy.value.includes("price") ? "price" : "sortNum",
      attribute:
        filters.attribute.length === 1 && filters.attribute.includes(0)
          ? []
          : filters.attribute,
      typeIds: filters.category.length > 0 ? filters.category : undefined,
      keyWord: searchKeyword.value.toLocaleUpperCase(),
      brandIds: filters.brand.length > 0 ? filters.brand : undefined,
    };

    if (isNextProduct) {
      params.isNextValPrice = true;
    }

    const response: any = await (isNextProduct
      ? getNextGoodsList
      : getGoodsList)(params);

    if (response.code === 1000) {
      products.value = response.data.list.map((item: Goods) =>
        transformToProduct(item)
      );
      totalProducts.value = response.data.pagination.total;
    } else {
      ElMessage.error(response.message || "获取商品列表失败");
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  }
}

// 在组件挂载时获取分类数据和商品列表
onMounted(() => {
  fetchCategories();
  fetchGoodsList();
  fetchBrands();
});

// 监听分页和筛选条件变化
watch(
  [currentPage, pageSize, filters, sortBy, onlyShowInStock, searchKeyword],
  () => {
    fetchGoodsList();
  }
);

// 效期标签映射
function getExpiryLabel(value: string): string {
  const map: Record<string, string> = {
    six_months_below: "六个月以内",
    six_months_above: "六个月以上",
  };
  return map[value] || "";
}

// 库存标签映射
function getStockLabel(value: string): string {
  const map: Record<string, string> = {
    in_stock: "有库存",
    out_of_stock: "无库存",
  };
  return map[value] || "";
}

// 添加获取属性标签的函数
function getAttributeLabels(values: number[]): string {
  return values
    .map((value) => {
      const attr = attributeOptions.find((opt) => opt.value === value);
      return attr ? attr.label : "";
    })
    .filter(Boolean)
    .join(", ");
}

// 重置过滤条件
function resetFilters() {
  filters.brand = [];
  filters.category = [];
  filters.expiry = "";
  filters.stock = "";
  filters.attribute = [];
  ElMessage.success("已清空筛选条件");
  // 清空 URL 查询参数
  router.replace({ query: {} });
}

// 应用过滤条件
function applyFilters() {
  ElMessage.success("筛选条件已应用");
  // 重置分页
  currentPage.value = 1;
}

// 分页处理
function handleSizeChange(val: number) {
  pageSize.value = val;
  // 获取对应页面数据
}

function handleCurrentChange(val: number) {
  currentPage.value = val;
  // 获取对应页面数据
}

const cartStore = useCartStore();
const userStore = useUserStore();

// 获取最小数量
function getMinQuantity(product: Product): number {
  // 如果是中包装且不支持拆零，最小数量为midpack
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.midpack;
  }
  return 1;
}

// 获取数量步长
function getQuantityStep(product: Product): number {
  // 如果是中包装且不支持拆零，步长为midpack
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.midpack;
  }
  return 1;
}

// 验证数量是否有效
function isValidQuantity(product: Product): boolean {
  // 如果是中包装且不支持拆零，数量必须是midpack的倍数
  if (product.midpack > 1 && product.isMidpackSaleDisabled === 1) {
    return product.quantity % product.midpack === 0;
  }
  return true;
}

// 添加到购物车
async function addToCart(product: Product) {
  if (parseFloat(product.storNum) <= 0) {
    ElMessage.warning("该商品已无库存");
    return;
  }

  // 验证数量
  if (!isValidQuantity(product)) {
    ElMessage.warning(`该商品不支持拆零，数量必须是${product.midpack}的倍数`);
    return;
  }

  // Prevent multiple clicks
  if (addingToCartIds.value.has(product.goodsId)) {
    return;
  }

  // Set loading state
  addingToCartIds.value.add(product.goodsId);

  try {
    const success = await cartStore.addItemToCart(
      product.goodsId,
      product.quantity
    );
  if (success) {
    const packingInfo =
      product.midpack > 1 && product.isMidpackSaleDisabled === 1
        ? `（按${product.midpack}${product.unit}计）`
        : "";

    ElMessage.success({
      message: `已将 ${product.quantity}【${product.oracleGoodsName}】${packingInfo}加入购物车`,
      duration: 2000,
    });

    // 重置数量为最小有效数量
    product.quantity = getMinQuantity(product);
  } else {
    // ElMessage.error('加入购物车失败')
  }
  } finally {
    // Always remove from loading state
    addingToCartIds.value.delete(product.goodsId);
  }
}

// 更新图片错误处理函数
function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement;
  if (img) {
    img.src = "/images/no.jpg";
  }
}

// 获取分类名称
function getCategoryName(categoryId: number): string {
  const findCategory = (categories: CategoryTreeNode[]): string | undefined => {
    for (const category of categories) {
      if (category.id === categoryId) {
        return category.label;
      }
      if (category.children && category.children.length > 0) {
        const found = findCategory(category.children);
        if (found) return found;
      }
    }
    return undefined;
  };

  return findCategory(categoryTree.value) || `分类 ${categoryId}`;
}

// 检查是否是父级分类
function isParentCategory(categoryId: number): boolean {
  return categoryTree.value.some((category) => category.id === categoryId);
}

// 获取要显示的分类ID列表
function getDisplayCategoryIds(): number[] {
  const parentIds = filters.category.filter((id: number) =>
    isParentCategory(id)
  );
  const childIds = filters.category.filter(
    (id: number) => !isParentCategory(id)
  );

  // 如果选中了父级分类，就不显示其子分类
  return parentIds.length > 0 ? parentIds : childIds;
}

// 跳转到商品详情页
function navigateToDetail(productId: string) {
  const url = `/product/${productId}`;
  window.open(url, '_blank');
}

// 格式化日期函数
function formatDate(dateString: string): string {
  if (!dateString) return "";

  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    return dateString;
  }
}

// 创建近效期订单
// 创建订单状态
const isCreatingOrder = ref(false)

async function createNextValOrder(product: Product) {
  if (parseFloat(product.storNum) <= 0) {
    ElMessage.warning("该商品已无库存");
    return;
  }

  // 验证数量
  if (!isValidQuantity(product)) {
    ElMessage.warning(`该商品不支持拆零，数量必须是${product.midpack}的倍数`);
    return;
  }

  if (isCreatingOrder.value) {
    return;
  }

  isCreatingOrder.value = true;

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确认下单 ${product.quantity} ${product.unit}【${product.oracleGoodsName}】？`,
      '确认下单',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 先添加到购物车
    const cartResponse = await cartStore.addItemToCart(
      product.goodsId,
      product.quantity,
      true
    );

    if (!cartResponse) {
      ElMessage.error("添加到购物车失败");
      return;
    }

    // 获取最新的购物车列表
    const cartListResponse = await getCartList();
    
    if (cartListResponse.code !== 1000 || !cartListResponse.data) {
      ElMessage.error("获取购物车列表失败");
      return;
    }

    // 找到刚刚添加的商品的购物车ID
    const cartItem = cartListResponse.data.find(
      (item) => item.goodsId === product.goodsId
    );

    if (!cartItem) {
      ElMessage.error("未找到购物车商品");
      return;
    }

    // 从购物车创建订单
    const orderResponse = await cartStore.createOrderFromCart([cartItem.id], undefined, true);

    if (orderResponse === true) {
      ElMessage.success("订单创建成功");
      // 重置数量为最小有效数量
      product.quantity = getMinQuantity(product);
      // 注意：不需要手动删除购物车商品，因为 createOrderFromCart 会自动更新购物车
    } else {
      ElMessage.error(typeof orderResponse === 'string' ? orderResponse : "订单创建失败");
      // 如果创建订单失败，清除购物车中的商品
      await deleteCart({ id: cartItem.id });
    }
  } catch (error) {
    console.error("创建订单失败:", error);
    ElMessage.error("创建订单失败");
  } finally {
    isCreatingOrder.value = false;
  }
}

// 添加品牌图片错误处理函数
function handleBrandImageError(event: Event) {
  const img = event.target as HTMLImageElement;
  if (img) {
    img.style.display = 'none'; // 隐藏加载失败的图片
  }
}

// 切换品牌选择状态
function toggleBrand(brandId: number) {
  const brandIdStr = brandId.toString();
  const index = filters.brand.indexOf(brandIdStr);
  
  if (index > -1) {
    // 如果已选择，则移除
    filters.brand.splice(index, 1);
  } else {
    // 如果未选择，则添加
    filters.brand.push(brandIdStr);
  }
}
</script>

<style scoped>
.filter-collapse {
  border-radius: 4px;
}

.filter-collapse :deep(.el-card__header) {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
}

.filter-collapse :deep(.el-card__body) {
  padding: 0 10px;
}

.filter-content {
  padding: 0;
}

/* 筛选项样式 */
.filter-category {
  display: flex;
  align-items: flex-start;
}

.filter-label {
  color: #606266;
  font-weight: 500;
}

.filter-options .el-checkbox,
.filter-options .el-radio {
  margin-right: 0;
}

/* 分类下拉菜单样式 */
.category-item {
  position: relative;
}

.subcategories {
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 100;
  width: auto;
}

.subcategory-wrapper {
  display: grid;
  gap: 8px;
}

.subcategory-item {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.subcategory-label {
  border-bottom: 1px dashed #eee;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  transition: color 0.2s ease;
}

.subcategory-label:hover {
  color: #409eff;
}

.subcategory-label.text-primary-500 {
  color: #409eff;
  font-weight: 600;
}

.third-level {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.third-category-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.third-category-item:hover {
  color: #409eff;
}

/* 标签样式 */
.selected-filters-area {
  border-top: 1px solid #ebeef5;
}

.tag-label {
  color: #606266;
  font-weight: 500;
  margin-right: 4px;
}

/* 商品卡片高级样式 */
.product-card {
  position: relative;
  background: #ffffff;
  border: 1px solid #f1f5f9;
  transition: all 0.3s ease;
  will-change: transform, box-shadow;
}

.product-card:hover {
  border-color: #e2e8f0;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1),
    0 4px 10px -2px rgba(0, 0, 0, 0.05);
}

/* 图片区域样式 */
.product-image {
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 50%, #f1f5f9 100%);
}

/* 标签样式 - 紧凑设计 */
.prescription-tag {
  display: inline-block;
  padding: 2px 6px;
  background: linear-gradient(135deg, #dc2626, #b91c1c);
  color: white;
  font-size: 10px;
  font-weight: 500;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(220, 38, 38, 0.3);
}

.package-tag {
  display: inline-block;
  padding: 2px 6px;
  color: white;
  font-size: 10px;
  font-weight: 500;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.package-mid {
  background: linear-gradient(135deg, #059669, #10b981);
}

.package-single {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

/* 库存标签 */
.stock-badge {
  display: inline-block;
  padding: 2px 6px;
  font-size: 10px;
  font-weight: 500;
  border-radius: 4px;
  backdrop-filter: blur(4px);
}

.stock-badge .text-red-600 {
  background: linear-gradient(135deg, #dc2626, #b91c1c) !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(220, 38, 38, 0.3);
}

.stock-badge .text-green-600 {
  background: linear-gradient(135deg, #059669, #10b981) !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(5, 150, 105, 0.3);
}

/* 商品名称 */
.product-name {
  color: #1e293b;
  font-weight: 500;
  line-height: 1.3;
  transition: color 0.3s ease;
  cursor: pointer;
}

.product-name:hover {
  color: #3b82f6;
}

/* 厂家信息 */
.manufacturer {
  color: #64748b;
  font-weight: 400;
}

/* 规格标签 */
.spec-tag {
  display: inline-block;
  padding: 2px 6px;
  background: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  color: #475569;
  font-size: 10px;
  font-weight: 500;
}

/* 包装信息 */
.package-info {
  font-weight: 500;
}

.no-split {
  color: red;
  font-weight: 600;
  margin-left: 4px;
}

/* 近效期标签 */
.expiry-tag {
  display: inline-block;
  padding: 4px 12px;
  background: linear-gradient(135deg, #fef08a, #fde047);
  border: 1px solid #eab308;
  border-radius: 6px;
  color: #854d0e;
  font-size: 13px;
  font-weight: 600;
  box-shadow: 0 2px 4px rgba(234, 179, 8, 0.2);
  transition: all 0.2s ease;
}

.expiry-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(234, 179, 8, 0.3);
}

/* 价格样式 */
.product-price {
  color: #dc2626;
  font-weight: 700;
  font-family: system-ui, -apple-system, sans-serif;
  letter-spacing: -0.025em;
}

/* 底部操作区 */
.bottom-section {
  align-items: center;
  margin-top: 8px;
}

/* 数量输入框 */
.quantity-input :deep(.el-input__wrapper) {
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: #ffffff;
  transition: all 0.3s ease;
  height: 28px;
}

.quantity-input :deep(.el-input__wrapper:hover) {
  border-color: #3b82f6;
}

.quantity-input :deep(.el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.quantity-input :deep(.el-input__inner) {
  font-size: 12px;
}

/* 购物车按钮 */
.cart-btn {
  background: linear-gradient(135deg, #3b82f6, #2563eb) !important;
  border: none !important;
  color: white !important;
  min-width: 32px !important;
  height: 28px !important;
  padding: 0 8px !important;
  border-radius: 6px !important;
  transition: all 0.3s ease !important;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.cart-btn:hover {
  background: linear-gradient(135deg, #2563eb, #1d4ed8) !important;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4) !important;
  transform: translateY(-1px) !important;
}

/* 近效期下单按钮 */
.cart-btn[type="success"] {
  background: linear-gradient(135deg, #059669, #10b981) !important;
  box-shadow: 0 2px 8px rgba(5, 150, 105, 0.3);
}

.cart-btn[type="success"]:hover {
  background: linear-gradient(135deg, #047857, #059669) !important;
  box-shadow: 0 4px 12px rgba(5, 150, 105, 0.4) !important;
}

/* 多行文本截断 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .product-grid {
    gap: 0.75rem;
  }

  .product-card {
    border-radius: 12px;
  }

  .product-info {
    padding: 0.75rem;
  }

  .product-image {
    height: 120px;
  }
}

/* 加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(15px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.product-card {
  animation: fadeInUp 0.4s ease-out forwards;
}

.product-card:nth-child(5n + 1) {
  animation-delay: 0ms;
}
.product-card:nth-child(5n + 2) {
  animation-delay: 40ms;
}
.product-card:nth-child(5n + 3) {
  animation-delay: 80ms;
}
.product-card:nth-child(5n + 4) {
  animation-delay: 120ms;
}
.product-card:nth-child(5n + 5) {
  animation-delay: 160ms;
}

/* 调整分页组件样式 */
.pagination :deep(.el-pagination) {
  justify-content: center;
}

/* 选中的checkbox和radio样式调整 */
.filter-option :deep(.el-checkbox.is-checked .el-checkbox__label),
.filter-option :deep(.el-radio.is-checked .el-radio__label) {
  color: #409eff;
}

/* 边框样式调整 */
.filter-option :deep(.el-checkbox--small.is-bordered),
.filter-option :deep(.el-radio--small.is-bordered) {
  padding: 4px 10px;
  border-radius: 4px;
}

/* 自定义品牌复选框样式 */
.custom-brand-checkbox {
  display: inline-block;
  padding: 12px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 160px;
  max-width: 220px;
  overflow: hidden;
  box-sizing: border-box;
}

.custom-brand-checkbox:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.custom-brand-checkbox.is-checked {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.custom-brand-checkbox.is-checked .brand-name {
  color: #409eff;
}

.brand-content {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
  overflow: hidden;
}

.brand-logo {
  width: 60px;
  height: 60px;
  object-fit: contain;
  transition: transform 0.2s ease;
  padding: 4px;
  border-radius: 4px;
  flex-shrink: 0;
}

.custom-brand-checkbox:hover .brand-logo {
  transform: scale(1.05);
}

.brand-name {
  font-size: 14px;
  color: #606266;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.2;
}

/* 品牌筛选区域布局优化 */
.filter-options {
  margin: -6px;  /* 恢复间距 */
}

.filter-option {
  padding: 6px;  /* 恢复间距 */
  margin: 0;
}

/* 品牌区域特殊样式 */
.filter-category .custom-brand-checkbox {
  margin-right: 12px;
  margin-bottom: 12px;
}
</style>
